/*
 * Assignment05c.c
 *
 * Created: 4/17/2015 9:06:40 PM
 *  Author: Jeevake Attapattu
 */ 

#define F_CPU 8000000UL //XTAL = 8MHZ
#include <avr/io.h>
#include <util/delay.h>

void ReadADC(uint16_t ADCchannel)
{
	int ADCval;
	ADMUX = (ADMUX & 0xF0)|(ADCchannel & 0x0F);//select channel
	ADCSRA |= 1<<ADSC;//start conversion
	while(ADCSRA & (1<<ADSC));//wait for conversion
	ADCval = ADC>>6;//use only upper 10 bits of 16 bits
	OCR1A = (int)ADCval*1.7+500;//Vin=ADC*Vref/1024 and 
	//0 degrees at OCR1A 500 ~180 degrees at 2200 gives slope of ~1.5 and intercept of 500 assuming linearity
	//exceeding certain values freezes servo
	//values were gathered through cpe 301 lab 08
	ADCSRA 	|= 	1<<ADSC;
}

int main()
{
	//initialize ADC
	ADMUX = (1<<REFS0)|(1<<ADLAR);//set Vref to 5V and left justify
	ADCSRA =(1<<ADIE)|(1<<ADEN);//set prescalar to 2, enable ADC interrupt and enable ADC
	ADCSRB = 0x00;//set ADC constant conversion
	DDRB = 0xFF;//Set PORTB pin as output
	//Fast PWM TOP = ICR1;
	//output compare OC1A 8 bit non inverted PWM, clear OC1A on Compare Match, set OC1A at TOP
	ICR1 = 20000;//ICR1 = 20000 defines 50Hz pwm
	TCCR1A=(0<<COM1A0)|(1<<COM1A1)|(0<<COM1B0)|(0<<COM1B1)|(1<<WGM11)|(0<<WGM10);//TCCR1A = 0x82
	TCCR1B=(1<<WGM13)|(1<<WGM12)|(0<<CS12)|(1<<CS11)|(0<<CS10);//TCCR1B = 0x1A start timer with prescaler 8
		
	while(1)
	{
		ReadADC(0);//set OCR1A from adc value
		_delay_ms(100);
	}
	return 0;
}